import { getToken, removeToken } from './auth'

// 基础配置 - 根据环境动态配置后端服务地址
const getBaseURL = () => {
  // #ifdef H5
  // H5环境下根据当前域名动态配置
  if (typeof window !== 'undefined') {
    const protocol = window.location.protocol
    const hostname = window.location.hostname
    if (hostname === 'localhost' || hostname === '127.0.0.1') {
      return 'http://localhost:8866'
    } else {
      return `${protocol}//${hostname}:8866`
    }
  }
  // #endif

  // 其他环境（小程序等）使用固定地址
  return 'http://localhost:8866'
}

const BASE_URL = getBaseURL()
const TIMEOUT = 60000


/**
 * HTTP请求封装
 */
class Request {
  constructor() {
    this.baseURL = BASE_URL
    this.timeout = TIMEOUT
  }

  /**
   * 请求拦截器
   */
  interceptRequest(config) {
    // 添加token
    const token = getToken()
    if (token) {
      config.header = {
        ...config.header,
        'Authorization': `Bearer ${token}`
      }
    }

    // 添加通用header
    config.header = {
      'Content-Type': 'application/json',
      ...config.header
    }

    console.log('请求配置:', config)
    return config
  }

  /**
   * 响应拦截器
   */
  interceptResponse(response) {
    console.log('响应数据:', response)

    const { data, statusCode } = response

    // HTTP状态码检查
    if (statusCode !== 200) {
      this.handleError(statusCode, '网络请求失败')
      return Promise.reject(response)
    }

    // 业务状态码检查
    if (data.code !== 200) {
      this.handleBusinessError(data)
      return Promise.reject(data)
    }

    return data
  }

  /**
   * 处理HTTP错误
   */
  handleError(statusCode, message) {
    let errorMsg = message

    switch (statusCode) {
      case 401:
        errorMsg = '登录已过期，请重新登录'
        removeToken()
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/auth/login'
        })
        break
      case 403:
        errorMsg = '没有访问权限'
        break
      case 404:
        errorMsg = '请求的资源不存在'
        break
      case 500:
        errorMsg = '服务器内部错误'
        break
      default:
        errorMsg = `网络错误 (${statusCode})`
    }

    uni.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 2000
    })
  }

  /**
   * 处理业务错误
   */
  handleBusinessError(data) {
    const { code, message } = data

    // 特殊错误码处理
    if (code === 401) {
      removeToken()
      uni.reLaunch({
        url: '/pages/auth/login'
      })
      return
    }

    // 显示错误信息
    uni.showToast({
      title: message || '操作失败',
      icon: 'none',
      duration: 2000
    })
  }



  /**
   * 通用请求方法
   */
  request(options) {
    return new Promise((resolve, reject) => {


      // 处理请求配置
      const config = {
        url: this.baseURL + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: options.header || {},
        timeout: options.timeout || this.timeout,
        ...options
      }
      config.url="http://localhost:8866/api" + options.url
      // 请求拦截
      const interceptedConfig = this.interceptRequest(config)

      // 发起请求
      uni.request({
        ...interceptedConfig,
        success: (response) => {
          try {
            const result = this.interceptResponse(response)
            resolve(result)
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          console.error('请求失败:', error)
          this.handleError(0, '网络连接失败')
          reject(error)
        }
      })
    })
  }

  /**
   * GET请求
   */
  get(url, params = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params
    })
  }

  /**
   * POST请求
   */
  post(url, data = {}) {
    return this.request({
      url,
      method: 'POST',
      data
    })
  }

  /**
   * PUT请求
   */
  put(url, data = {}) {
    return this.request({
      url,
      method: 'PUT',
      data
    })
  }

  /**
   * DELETE请求
   */
  delete(url, params = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data: params
    })
  }

  /**
   * 文件上传
   */
  upload(url, filePath, name = 'file', formData = {}) {
    return new Promise((resolve, reject) => {
      const token = getToken()

      uni.uploadFile({
        url: 'http://localhost:8866/api' + url,
        filePath,
        name,
        formData,
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (response) => {
          try {
            const data = JSON.parse(response.data)
            if (data.code === 200) {
              resolve(data)
            } else {
              this.handleBusinessError(data)
              reject(data)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          console.error('上传失败:', error)
          this.handleError(0, '文件上传失败')
          reject(error)
        }
      })
    })
  }
}

// 创建实例
const request = new Request()

export default request
